import httpInstance from './http-instance'
import API from '@/apis'
import { normalToast } from './utils'

export default async function (funcName, data = {}, requestSetting = {}) {
  const requestData = { ...data }

  // if (!Object.keys(data).includes('supplierId')) {
  //   requestData.supplierId = ''
  // }

  const { ...res } = API
  const config = { ...res }

  const { headers } = requestSetting || {}

  if (typeof config[funcName] !== 'object') {
    throw new Error('调用api函数函数错误，请检查函数名称是否错误')
  }

  config[funcName].method = (config[funcName].method || 'get').toLocaleUpperCase()

  const newConfig = JSON.parse(JSON.stringify(config[funcName]))

  if (requestData) {
    newConfig.url = newConfig.url.replace(/\{([\d\w_-]+)\}/g, (word, $1) => {
      const res = data[$1] || ''
      delete data[$1]
      return res
    })
    newConfig.data = requestData
  }

  newConfig.headers = Object.assign(config[funcName].headers || {}, headers)
  try {
    const result = await httpInstance.request(newConfig)

    if (Number(result.data?.errcode) !== 0) {
      const title = result.data.msg || ERROR_MESSAGE
      normalToast(title)
      return Promise.resolve(result)
    }

    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
